package com.example.sevicedemo

import android.app.Activity
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.work.*
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * @author ypk
 * 创建日期：2021/11/25  13:38
 * 描述：
 */
public const val TAG = "SimpleWorker"

class SimpleWorker(context: Context, params: WorkerParameters) : Worker(context, params) {

    override fun doWork(): Result {
        println("SimpleWorker.doWork 这里是子线程，可以用耗时任务")

        return Result.success()
    }


    companion object {

        fun startWorker(context: AppCompatActivity) {
            println("SimpleWorker.startWorker")
            cancelWorker(context, TAG)

            val request = OneTimeWorkRequest.Builder(SimpleWorker::class.java)
                .addTag(TAG)
                .setInitialDelay(5, TimeUnit.SECONDS)
                //第二个参数和第三个参数用于指定在多久之后重新执行任务，时间最短不能少于10秒钟。第一个参数用户指定下次重试的时间应该以什么样的形式延迟。
                .setBackoffCriteria(BackoffPolicy.LINEAR, 10, TimeUnit.SECONDS)
                .build()


            //周期性允许的任务，周期间隔不能短于15分钟
            val requestPeriodic =
                PeriodicWorkRequest.Builder(SimpleWorker::class.java, 15, TimeUnit.MINUTES)
                    .build()


            WorkManager.getInstance(context).enqueue(request)


            WorkManager.getInstance(context)
                .getWorkInfoByIdLiveData(request.id)
                .observe(context) { workInfo ->
                    if (workInfo.state == WorkInfo.State.SUCCEEDED) { println("MainActivity.onCreate SUCCEEDED")

                    } else if (workInfo.state == WorkInfo.State.FAILED) {
                        println("MainActivity.onCreate FAILED")
                    }
                }


        }


        fun cancelWorker(context: Context, id: UUID) {
            WorkManager.getInstance(context).cancelWorkById(id)
        }

        fun cancelWorker(context: Context, tag: String) {
            WorkManager.getInstance(context).cancelAllWorkByTag(tag)
        }

        fun cancelAllWork(context: Context) {
            WorkManager.getInstance(context).cancelAllWork()
        }

    }
}